//
//  FansAmuseViewController.m
//  艾听歌
//
//  Created by dllo on 16/5/14.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "FansAmuseViewController.h"
//#import "MusicPlyController.h"
#import "AllTravelTableViewCell.h"
#import "AllTravel.h"
#import "Product.h"
#import "TabalViewController.h"
#import "AllTravelTableViewCell.h"

#import "DetailViewController.h"



#define allCELL @"cell"
#define travelcell @"cell"

@interface FansAmuseViewController ()<UIScrollViewDelegate, UITableViewDataSource, UITableViewDelegate>
@property(nonatomic, strong) UITableView *tableView;
@property(nonatomic, strong) NSMutableArray *dataArr;// 数据
@property(nonatomic, strong) NSMutableArray *titleArr;/**< 自定义标题 */
@property(nonatomic, strong) UIView *lineView;/**< 下划线 */
@property(nonatomic, strong) UIColor *lineColor;/**< 下划线颜色 */
@property(nonatomic, assign) CGFloat titlePadding;/**< 设置标题间距 */
@property(nonatomic, assign) CGFloat lineHeight;/**< 设置下划线高度 */
@property(nonatomic, strong) UIScrollView *titleScrollerView;/**< 标题内容scrollerView */
@property(nonatomic, strong) NSMutableArray *titleBtnArr;/**< 装按钮的数组 */
@property(nonatomic, assign, getter=isHidden) BOOL lineIsHidden;/**< 下划线是否隐藏 */
@property(nonatomic, assign) CGFloat timer;/**< 下划线切换时间 */
@property(nonatomic, strong) NSMutableArray *controllerArr;/**< 控制器数组 */
@property(nonatomic, assign) CGFloat buttonWidth;/**< 按钮宽度 */
@property(nonatomic, strong) UIView *subView;/**< 添加上的View */
@property(nonatomic, strong) NSMutableArray *idArr;/**< 各国id */
@property(nonatomic, strong) UIButton *titleBtn;
@property(nonatomic, assign) NSInteger i;/**< 储存下标 */
@property(nonatomic, strong) UICollectionView *collection;

@end

@implementation FansAmuseViewController

- (void)viewDidLoad {
    [super viewDidLoad];
     //数组初始化
    //接收数据的数组一定要放在这 ,方便刷新
    self.dataArr = [NSMutableArray array];
    self.controllerArr = [NSMutableArray array];
    self.titleBtnArr = [NSMutableArray array];
//    self.controllerArr = [NSMutableArray array];
    
    self.view.dk_backgroundColorPicker = DKColorPickerWithRGB(0xFFFFFF, 0x9C9C9C);
    
//    self.view.backgroundColor = [UIColor whiteColor];
    
    //导航栏上的标题
    UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(self.view.center.x - 30, 10, 60, 30)];
    title.text = @"自由行 🍁 随心选";
    title.textColor = [UIColor whiteColor];
    title.textAlignment = NSTextAlignmentCenter;
    self.navigationItem.titleView = title;
    
    //导航栏的背景颜色
//    self.navigationController.navigationBar.backgroundColor = [UIColor colorWithRed:255 / 255.0 green:204 / 255.0 blue:255 / 255.0 alpha:1];
     self.navigationController.navigationBar.dk_barTintColorPicker = DKColorPickerWithRGB(0xFF6EB4, 0x9C9C9C);
    //调整坐标
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    //滚动标题视图的定义
    self.titleScrollerView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 64, [UIScreen mainScreen].bounds.size.width, 40)];
    [self.view addSubview:self.titleScrollerView];
 
    
    //滚动标题中下划线的定义
    self.lineColor = [UIColor colorWithRed:255 / 255.0 green:133 / 255.0 blue:165 / 255.0 alpha:1]; // 下划线颜色
    self.titlePadding = 20; // 标题间距
    self.lineHeight = 1; // 下划线高度
    self.lineIsHidden = NO; // 下划线是否隐藏
    self.timer = 0.5; // 下划线切换时间
    self.buttonWidth = 50; // 按钮宽度
    self.i = 0;
    // 标题数组
    self.titleArr = [NSMutableArray arrayWithObjects:@"全部",@"泰国",@"日本",@"美国",@"新加坡",@"香港",@"澳大利亚", @"新西兰", @"韩国", @"台湾", @"越南", @"南非", @"中国", nil];
    // 标题id数组
    self.idArr = [NSMutableArray arrayWithObjects:@"0", @"3649", @"3808", @"3803", @"3589", @"3814", @"3735", @"3673", @"3238", @"3660", @"3708", @"3426", @"3793", nil];
    
    //调用函数,从网络上获取数据
//    [self dataHandle];
    [self GetDataHandle];

    
    //调用方法,创建tableview
    [self createTableView];
    
    //添加按钮
    for (int i = 0; i < self.titleArr.count; i++) {
        //计算按钮内部文字的长度
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[NSFontAttributeName] = [UIFont systemFontOfSize:15];
        dict[NSForegroundColorAttributeName] = [UIColor grayColor];
//        dict[NSForegroundColorAttributeName] = DKColorPickerWithRGB(0x9C9C9C,0xFF6EB4);
        self.buttonWidth = 60;
        //无法处理多个不同长度的标题排列 限定每个标题字符长度相同
        UIButton *titleBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        titleBtn.frame = CGRectMake(i * (self.buttonWidth + self.titlePadding), 5, 60, 30);
        [titleBtn setTitleColor:[UIColor yellowColor] forState:(UIControlStateHighlighted)];
        titleBtn.tag = i;
//        titleBtn.backgroundColor = [UIColor colorWithRed:255 / 255.0 green:133 / 255.0 blue:160 / 255.0 alpha:1];
        titleBtn.dk_backgroundColorPicker = DKColorPickerWithRGB(0xFF6EB4, 0x9C9C9C);
        titleBtn.layer.borderWidth = 1;
        titleBtn.layer.cornerRadius = 15;
        titleBtn.layer.borderColor = [[UIColor colorWithRed:255 / 255.0 green:133 / 255.0 blue:160 / 255.0 alpha:1] CGColor];
        titleBtn.layer.masksToBounds = YES;
        [self.titleScrollerView addSubview:titleBtn];
        [self.titleBtnArr addObject:titleBtn];
        
    }
    
    
    //获取滚动标题的滚动长度
    UIButton *btn = [self.titleBtnArr lastObject];
    CGFloat maxW = CGRectGetMaxX(btn.frame);
    self.titleScrollerView.contentSize = CGSizeMake(maxW, 0);
    self.titleScrollerView.showsHorizontalScrollIndicator = NO;
    
    // 标题按钮设置
    for (int i = 0; i < self.titleArr.count; i++) {
        self.titleBtn = self.titleBtnArr[i];
        self.titleBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        [self.titleBtn setTitle:self.titleArr[i] forState:UIControlStateNormal];
        [self.titleBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [self.titleBtn.titleLabel sizeToFit];
        // 按钮点击
        [self.titleBtn addTarget:self action:@selector(btnDidClick:) forControlEvents:UIControlEventTouchUpInside];
        //添加下划线
        if (i == 0) {
            UIView *lineView = [[UIView alloc] init];
            self.lineView = lineView;
            self.lineView.backgroundColor = self.lineColor;
            CGFloat lineW = self.titleBtn.frame.size.width;
            CGFloat lineY = CGRectGetMaxY(self.titleBtn.frame) + 3;
            self.lineView.frame = CGRectMake(self.titleBtn.frame.origin.x, lineY, lineW, self.lineHeight);
            [self.titleScrollerView addSubview:self.lineView];
        }
        
    }
    
#pragma mark---通知中心第一步:注册一个通知
    //参数name:是消息通知的标识符,只有发送者跟接受者的name参数一样,接收者才能接收到发送者的消息.
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(tocolletionDetail:) name:@"tocolletionDetail" object:nil];

     
}


//通知中心方法的实现
- (void)tocolletionDetail:(NSNotification *)noti
{
    
    TabalViewController *tableVC = [[TabalViewController alloc]init];
    tableVC.proModel = [noti object];
    
    [self.navigationController pushViewController:tableVC animated:YES];
    
    
}


// 创建tableView
- (void)createTableView
{
   
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 104, self.view.frame.size.width, HEIGHT - 150) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.rowHeight = 450;
    self.tableView.separatorColor = [UIColor clearColor];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.tableView];
    [self.tableView registerClass:[AllTravelTableViewCell class] forCellReuseIdentifier:allCELL];

}

- (void)GetDataHandle
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSString *str = [NSString stringWithFormat:@"http://web.breadtrip.com/product/topics/more/?start=0&count=10&country=%@",self.idArr[self.i]];
    [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"text/html", @"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css", @"text/plain", @"application/x-javascript", @"application/javascript",nil]];
    [WTAFNetWorking WT_GetWithURL:str Parameter:nil success:^(id result) {
        NSMutableDictionary *dataDic = [result objectForKey:@"data"];
        NSArray *array = dataDic[@"topic_list"];
        
        for (NSDictionary *dic in array) {
            AllTravel *model = [[AllTravel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [self.dataArr addObject:model];
        }
        
        [self.tableView reloadData];

        
    } error:^(NSError *error) {
        
        
    }];
    
}



// 数据解析
- (void)dataHandle {
    //接收数据的数组一定要放在这 ,方便刷新
    self.dataArr = [NSMutableArray array];

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//    NSLog(@"%@",self.idArr[self.i]);
    NSString *str = [NSString stringWithFormat:@"http://web.breadtrip.com/product/topics/more/?start=0&count=10&country=%@",self.idArr[self.i]];
    [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"text/html", @"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css", @"text/plain", @"application/x-javascript", @"application/javascript",nil]];
    [manager GET:str parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        
        NSMutableDictionary *dataDic = [responseObject objectForKey:@"data"];
        NSArray *array = dataDic[@"topic_list"];
        
        for (NSDictionary *dic in array) {
            AllTravel *model = [[AllTravel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [self.dataArr addObject:model];
        }
        
        [self.tableView reloadData];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"%@",error);
    }];
    
    

}

// 按钮点击方法
- (void)btnDidClick:(UIButton *)button {
    
    if (!_lineIsHidden) {
        self.timer = 0.2;
        [UIView animateWithDuration:self.timer animations:^{
            if (self.lineHeight) {
                CGFloat lineViewX = button.frame.origin.x;
                CGFloat lineViewY = self.lineView.frame.origin.y;
                CGFloat lineViewW = button.frame.size.width;
                self.lineView.frame = CGRectMake(lineViewX, lineViewY, lineViewW, 1);
            }
        } completion:^(BOOL finished) {
//            NSLog(@"%ld", button.tag);
            self.i = button.tag;
            [self dataHandle];
            [self.tableView reloadData];
        }];
    }
    
}



#pragma mark - tableView协议方法
// 行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
      return self.dataArr.count;
//    return 5;
}

// cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    

    
        AllTravelTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:allCELL forIndexPath:indexPath];
//        cell.backgroundColor = [UIColor colorWithRed:255 / 255.0 green:254 / 255.0 blue:249 / 255.0 alpha:1];
    cell.dk_backgroundColorPicker = DKColorPickerWithRGB(0xffffff, 0x9c9c9c);
    
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.tableCellModel = self.dataArr[indexPath.row];
    
    __weak FansAmuseViewController *root = self;
    cell.toDetailBlock = ^(AllTravel *model){
        
        DetailViewController *DetailVC = [[DetailViewController alloc]init];
        
        DetailVC.detailModel = model;
        
        [root.navigationController pushViewController:DetailVC animated:YES];
    
    };
    
        return cell;
//    }else{
//        TravelTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:travelcell forIndexPath:indexPath];
//        cell.selectionStyle = UITableViewCellSelectionStyleNone;
//      cell.backgroundColor = [UIColor colorWithRed:255 / 255.0 green:254 / 255.0 blue:249 / 255.0 alpha:1];
//        return cell;
//    }
//    
    
//    cell.tId = [self.idArr objectAtIndex:self.i];
    
}




    
    

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
